<template>
  <view v-if="!isConnected && show" class="network-status-bar" :class="type">
    <text class="status-text">{{ statusText }}</text>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'

// 定义 props
const props = defineProps({
  // 是否显示
  show: {
    type: Boolean,
    default: true
  },
  // 类型：offline(离线提示), online(在线提示)
  type: {
    type: String,
    default: 'offline'
  }
})

// 定义 emits
const emit = defineEmits(['networkChange'])

// 响应式数据
const isConnected = ref(true)
const networkType = ref('unknown')

// 计算属性
const statusText = computed(() => {
  if (props.type === 'offline') {
    return networkType.value === 'none' ? '网络已断开，请检查网络设置' : `${networkType.value}网络`
  } else {
    return `网络已连接: ${networkType.value}`
  }
})

// 获取当前网络状态
const getNetworkType = () => {
  uni.getNetworkType({
    success: (res) => {
      networkType.value = res.networkType
      isConnected.value = res.networkType !== 'none'
    }
  })
}

// 监听网络状态变化
const listenNetworkStatus = (res) => {
  networkType.value = res.networkType
  isConnected.value = res.isConnected
  emit('networkChange', res)
}

// 生命周期钩子
onMounted(() => {
  getNetworkType()
  uni.onNetworkStatusChange(listenNetworkStatus)
})

onUnmounted(() => {
  // 取消监听网络状态变化
  uni.offNetworkStatusChange()
})
</script>

<style scoped>
.network-status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  padding: 10rpx 20rpx;
  text-align: center;
  z-index: 9998;
  font-size: 24rpx;
}

.network-status-bar.offline {
  background-color: #dd524d;
  color: white;
}

.network-status-bar.online {
  background-color: #4cd964;
  color: white;
}

.status-text {
  display: block;
}
</style>